'use strict';

define(['controllers', '../service/menuService'], function(controllers) {
    controllers.common.controller('NavController', ['$scope', '$location', '$rootScope', 'MenuService', function ($scope, $location, $rootScope, menuService) {

        $rootScope.menus = menuService.getMenus();
        $rootScope.menuIdMap = menuService.getMenuIdMap();
        $rootScope.menuUrlMap = menuService.getMenuUrlMap();
        $rootScope.collectionMap = menuService.getCollectionMap();
        $rootScope.collectionSortedMap = menuService.getCollectionSortMap();
        $rootScope.defaultMenu = menuService.getDefaultMenu();

        $scope.account = getAccountFromCookie();

        function locationChange() {
            var path = $location.path();
            var menuUrl = menuService.getOriginMenuUrl(path);
            var menu = $rootScope.menuUrlMap[menuUrl];
            if (menu != null) {
                $scope.activeView = menu.parentId == null ? menu.name : $rootScope.menuIdMap[menu.parentId].name;
            } else {
                $scope.activeView = $rootScope.defaultMenu.name;
            }
        }

        locationChange();

        $scope.$on('$locationChangeSuccess', function(event, path) {
            locationChange();
        });

        $scope.hasChild = function(menu) {
            return menu.children != null && menu.children.length > 0;
        };

        $scope.collectionMenuClick = function(collectionId, menu) {
            $location.path(menu.children[0].url.replace(':id', collectionId));
        };
    }]);
});